package com.ruoyi.djData.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ExportWordUtils;
import com.ruoyi.djData.domain.pad.DjTaskResqDTO;
import com.ruoyi.djData.domain.plat.DataDj;
import com.ruoyi.djData.mapper.DataDjMapper;
import com.ruoyi.djData.service.IDataDjService;
import com.ruoyi.djData.utils.GonglvxiangUtils;
import com.ruoyi.task.domain.entity.DataTaskEntity;
import com.ruoyi.task.service.IDataTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

/**
 * 电机数据处理Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-01-17
 */
@Service
public class DataDjServiceImpl implements IDataDjService
{
    @Autowired(required = false)
    private DataDjMapper dataDjMapper;

    @Autowired(required = false)
    private IDataTaskService dataTaskService;

    /**
     * 查询电机数据处理
     * 
     * @param djId 电机数据处理主键
     * @return 电机数据处理
     */
    @Override
    public DataDj selectDataDjByDjId(Long djId)
    {
        return dataDjMapper.selectDataDjByDjId(djId);
    }

    /**
     * 查询电机数据处理列表
     * 
     * @param dataDj 电机数据处理
     * @return 电机数据处理
     */
    @Override
    public List<DataDj> selectDataDjList(DataDj dataDj)
    {
        return dataDjMapper.selectDataDjList(dataDj);
    }

    /**
     * 新增电机数据处理
     * 
     * @param dataDj 电机数据处理
     * @return 结果
     */
    @Override
    public int insertDataDj(DataDj dataDj)
    {
        dataDj.setCreateTime(DateUtils.getNowDate());
        return dataDjMapper.insertDataDj(dataDj);
    }

    /**
     * 修改电机数据处理
     * 
     * @param dataDj 电机数据处理
     * @return 结果
     */
    @Override
    public int updateDataDj(DataDj dataDj)
    {
        dataDj.setUpdateTime(DateUtils.getNowDate());
        return dataDjMapper.updateDataDj(dataDj);
    }

    /**
     * 批量新增电机数据
     *
     * @param dataDjs
     */
    @Override
    public int batchDataDj(List<DataDj> dataDjs) {
        return dataDjMapper.batchDataDj(dataDjs);
    }

    /**
     * 批量删除电机数据处理
     * 
     * @param djIds 需要删除的电机数据处理主键
     * @return 结果
     */
    @Override
    public int deleteDataDjByDjIds(Long[] djIds)
    {
        return dataDjMapper.deleteDataDjByDjIds(djIds);
    }

    /**
     * 删除电机数据处理信息
     * 
     * @param djId 电机数据处理主键
     * @return 结果
     */
    @Override
    public int deleteDataDjByDjId(Long djId)
    {
        return dataDjMapper.deleteDataDjByDjId(djId);
    }

    /**
     * 删除电机数据处理
     *
     * @param dataTaskId
     * @return 结果
     */
    @Override
    public int deleteDataDjByDataTaskId(Long dataTaskId) {
        return dataDjMapper.deleteDataDjByDataTaskId(dataTaskId);
    }

    /**
     * 变更电机数据状态
     *
     * @param dataTaskId
     * @return
     */
    @Override
    public int updateDataDjByDataTaskId(Long dataTaskId) {
        //变更任务状态
        try {
            Long[] dataTaskIds = new Long[] {dataTaskId};
            dataTaskService.deleteDataTaskByDataTaskIds(dataTaskIds, "001");
        }catch (Exception e){
            e.printStackTrace();
        }
        return dataDjMapper.updateDataDjByDataTaskId(dataTaskId);
    }

    /**
     * 变更电机数据状态
     *
     * @param djId
     * @return
     */
    @Override
    public int updateDataKDjByDId(Long djId) {
        return dataDjMapper.updateDataKDjByDId(djId);
    }

    /**
     * 根据任务id获取所有电机数据
     *
     * @param dataTaskId
     * @return
     */
    @Override
    @Async("threadPoolKy")
    public Future<List<DataDj>> selectAllByDataTaskId(Long dataTaskId) {
        return new AsyncResult<>(dataDjMapper.selectAllByDataTaskId(dataTaskId));
    }

    /**
     * 根据任务Id获取空压机任务数据
     *
     * @param dataTaskId
     */
    @Override
    public DjTaskResqDTO selectDjTaskByDataTaskId(Long dataTaskId) throws ExecutionException, InterruptedException {
        long startTime = System.currentTimeMillis();
        Future<DataTaskEntity> taskFuture = dataTaskService.selectDataTask(dataTaskId);
        Future<List<DataDj>> resultListFuture = selectAllByDataTaskId(dataTaskId);
        DjTaskResqDTO djTaskDTO = new DjTaskResqDTO();
        boolean isGetDataTaskEntity = false;
        boolean isGetDataKyjEntityList = false;
        while (!isGetDataTaskEntity || !isGetDataKyjEntityList) {
            Thread.sleep(10);
            if (taskFuture.isDone() || taskFuture.isCancelled()) {
                isGetDataTaskEntity = true;
                if (taskFuture.isDone()) {
                    DataTaskEntity dataTaskEntity = taskFuture.get();
                    djTaskDTO.setDataTaskEntity(dataTaskEntity);
                }
            }
            if (resultListFuture.isDone() || resultListFuture.isCancelled()) {
                isGetDataKyjEntityList = true;
                if (resultListFuture.isDone()) {
                    List<DataDj> datadjEntityList = resultListFuture.get();
                    if (!CollectionUtils.isEmpty(datadjEntityList)) {
                        datadjEntityList.forEach(item -> {
                            item.setDypchl(dypcCac(item));
                            item.setBphdhl(bphdCac(item));
                        });
                        djTaskDTO.getResultList().addAll(datadjEntityList);
                    }
                }
            }
        }
        System.out.println("kyjTaskDTO = 电机机机测试数据数据查询用时 " + (System.currentTimeMillis() - startTime));
        return djTaskDTO;
    }

    /**
     * 电机参数修改
     *
     * @param dataDj
     */
    @Override
    public DataDj modifyDjParam(DataDj dataDj) {
        return GonglvxiangUtils.calculateFunc(dataDj);
    }

    /**
     * 电机报告导入
     *
     * @param dataDj
     */
    @Override
    public String dataDjImportReport(DataDj dataDj) {
        // 报告模板名称
        String template = dataDj.getTempId();
        //测试任务信息
        DataTaskEntity dataTaskEntity = dataTaskService.selectDataTaskByDataTaskId(dataDj.getDataTaskId());
        //参数变更
        dataDjMapper.updateDataDj(dataDj);
        Map<String, Object> params = new HashMap<>();
        /* ===========  测试任务信息 */
        if (dataTaskEntity != null) {
            params.put("受检单位", dataTaskEntity.getShjdw());
            params.put("设备名称", dataTaskEntity.getShbbh());
            params.put("检测日期", DateUtils.dateTime(dataTaskEntity.getTaskCreateTime()));
            params.put("主检人员", dataTaskEntity.getZhjxm());
            params.put("测试人员", dataTaskEntity.getCshry());
        }
        /* ===========  参数、结果 */
        if (dataDj != null) {
            params.put("额定电压", dataDj.getDjEddy());
            params.put("额定电流", dataDj.getDjEddl());
            params.put("额定功率", dataDj.getDjEdgl());
            params.put("额定效率", dataDj.getDjEdxl());
            params.put("空载电流", dataDj.getDjKzdl());
            params.put("空载功率", dataDj.getDjKzgl());
            params.put("无功经济当量", dataDj.getDjWgjjdl());
            params.put("额定综合效率", dataDj.getEdzhxl());
            params.put("允许综合效率", GonglvxiangUtils.getNormalFloat(dataDj.getEdzhxl()) * 0.6f);
            params.put("功率因数", dataDj.getGlysh());
            params.put("A相电压", dataDj.getUA());
            if (dataDj.getDjCshff().equals("单瓦")) {//单瓦法
                params.put("B相电压", "--");
                params.put("C相电压", "--");
            } else {//三瓦法
                params.put("B相电压", dataDj.getUB());
                params.put("C相电压", dataDj.getUC());
            }
            params.put("平均电压", dataDj.getPjdy());
            params.put("电压不平衡度", dataDj.getSxbphd());
            params.put("A相电流", dataDj.getIA());
            if (dataDj.getDjCshff().equals("单瓦")) {//单瓦法
                params.put("B相电流", "--");
                params.put("C相电流", "--");
            } else if (dataDj.getDjCshff().equals("双瓦")) {//双瓦法
                params.put("B相电流", "--");
                params.put("C相电流", dataDj.getIC());
            } else {//三瓦法
                params.put("B相电流", dataDj.getIB());
                params.put("C相电流", dataDj.getIC());
            }
            params.put("平均电流", dataDj.getPjdl());
            params.put("功率A", GonglvxiangUtils.getNormalFloat(dataDj.getAyggl()) / 1000f);
            if (dataDj.getDjCshff().equals("单瓦")) {//单瓦法
                params.put("功率B", "--");
                params.put("功率C", "--");
            } else if (dataDj.getDjCshff().equals("双瓦")) {//双瓦法
                params.put("功率B", "--");
                params.put("功率C", GonglvxiangUtils.getNormalFloat(dataDj.getCyggl()) / 1000f);
            } else {//三瓦法
                params.put("功率B", GonglvxiangUtils.getNormalFloat(dataDj.getByggl()) / 1000f);
                params.put("功率C", GonglvxiangUtils.getNormalFloat(dataDj.getCyggl()) / 1000f);
            }
            params.put("UAB", dataDj.getUAB());
            if (dataDj.getDjCshff().equals("单瓦")) {//单瓦法
                params.put("UBC", "--");
                params.put("UCA", "--");
            } else {//三瓦法
                params.put("UBC", dataDj.getUBC());
                params.put("UCA", dataDj.getUCA());
            }
            params.put("平均相电压", dataDj.getPjxdy());
            params.put("有功功率", dataDj.getYggl());
            params.put("无功功率", dataDj.getWggl());
            params.put("视在功率", dataDj.getShzgl());
            params.put("输出功率", dataDj.getShchgl());
            params.put("运行效率", dataDj.getDjxl());
            params.put("综合效率", dataDj.getZhxl());
            params.put("负载系数", dataDj.getFzxsh());
        }
        String docRootPath = RuoYiConfig.getProfile() + RuoYiConfig.getDocumentPath() + "/";
        String docFileName = System.currentTimeMillis() + "-dj.docx";
        boolean isOk = ExportWordUtils.exportWord(RuoYiConfig.getProfile() + RuoYiConfig.getTemplatePath() + "/" + template, docRootPath, docFileName, params);
        System.out.println("isOK: 生成测试报告" + isOk + " docFileName: " + docFileName);
        if(isOk) {
            return "/profile/document/" + docFileName;
        }else {
            return "";
        }
    }

    /**
     * 电压偏差计算
     */
    public String dypcCac(DataDj dataDj) {
        if (GonglvxiangUtils.getNormalFloat(dataDj.getPjxdy()) / GonglvxiangUtils.getNormalFloat(dataDj.getDjEddy()) > 0.9f) {
            return "合理";
        } else {
            return "不合理";
        }
    }

    /**
     * 不平衡度计算
     */
    public String bphdCac(DataDj dataDj) {
        if (GonglvxiangUtils.getNormalFloat(dataDj.getSxbphd()) > 1.5f) {
            return "不合理";
        } else {
            return "合理";
        }
    }

}
